package media

import (
	"errors"
	"server/common"

	"github.com/mitchellh/mapstructure"
)

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) checkConnectTransportReqData(data common.ConnectTransportReqData) error {
	// Check if transport type is provided
	if data.TransportType == "" {
		return errors.New("transport type is required in connect WebRTC transport request")
	}

	// Only support webrtc transport for now
	if data.TransportType != common.WEBRTC_TRANSPORT {
		return errors.New("only WebRTC transport is supported in connect transport request")
	}

	// Check if transport ID is provided
	if data.TransportId == "" {
		return errors.New("transport ID is required in connect WebRTC transport request")
	}

	// Check if DTLS parameters are provided
	if data.DtlsParameters == nil {
		return errors.New("DTLS parameters are required in connect WebRTC transport request")
	}

	return nil
}

// -------------------------------------------------------------------------------------------------
//
// -------------------------------------------------------------------------------------------------
func (s *MediaService) handleConnectTransportReq(msg common.Message) {
	LOG(msg.Rid).WithField("msg", common.ToJson(msg)).Info(
		"handling connect WebRTC transport request")

	var reqData common.ConnectTransportReqData
	if err := mapstructure.Decode(msg.Data, &reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error(
			"failed to decode connect WebRTC transport request data")
		return
	}

	if err := s.checkConnectTransportReqData(reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("invalid connect WebRTC transport request data")
		return
	}

	if err := s.ConnectTransport(msg.Rid, reqData); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to connect WebRTC transport")
		return
	}

	resMsg := common.Message{
		Rid: msg.Rid,
		Cmd: common.CONNECT_TRANSPORT_RES,
		Data: common.ResMsgData{
			Code: 0,
			Msg:  "Transport connected successfully",
		},
	}
	if err := s.wsClient.Send(resMsg); err != nil {
		LOG(msg.Rid).WithError(err).Error("failed to send connect transport response")
	}
}
